let startX
let startY
let endX
let endY
let onLeftScroll
let onRightScroll
let onOtherScroll
let startTime
let endTime

export default function (el, leftScroll, rightScroll, otherScroll) {
  onLeftScroll = leftScroll
  onRightScroll = rightScroll
  onOtherScroll = otherScroll
  // var el = document.getElementsByTagName("body")[0];
  el.addEventListener('touchstart', handleStart, false)
  el.addEventListener('touchend', handleEnd, false)


}
function debounce (fn, wait) {
  let timer = null
  return function () {
    if (timer !== null) {
      clearTimeout(timer)
    }
    timer = setTimeout(fn, wait)
  }
}
function handleStart (e) {
  startTime = new Date().getTime()
  startX = e.touches[0].pageX
  startY = e.touches[0].pageY
  e = e || window.event

}
function handleEnd (e) {
  endTime = new Date().getTime()
  endX = e.changedTouches[0].pageX
  endY = e.changedTouches[0].pageY
  upOrDown(startX, startY, endX, endY)

}
function upOrDown (startX, startY, endX, endY) {

  let direction = GetSlideDirection(startX, startY, endX, endY)
  switch (direction) {
    case 0:
      // alert("没滑动");
      onOtherScroll()
      break
    case 1:
      // alert("向上");
      onOtherScroll()
      break
    case 2:
      // alert("向下");
      onOtherScroll()
      break
    case 3:
      // alert("向左");
      onLeftScroll()
      break
    case 4:
      // alert("向右");
      onRightScroll()
      break
    default:
      onOtherScroll()
      break
  }
}

function GetSlideDirection (startX, startY, endX, endY) {
  let dy = startY - endY
  let dx = endX - startX
  let result = 0
  // 如果滑动距离太短
  if (Math.abs(dx) > 50 || Math.abs(dy) > 5) {
  } else {
    return result
  }

  let speed = Math.abs(dx) / (endTime - startTime)
  if (speed < 0.3) {
    // 慢速滑动
    return result
  }
  let angle = GetSlideAngle(dx, dy)
  if (angle >= -45 && angle < 45) {
    if (Math.abs(dx) > 50) {
      result = 4
    }
  } else if (angle >= 45 && angle < 135) {
    result = 1
  } else if (angle >= -135 && angle < -45) {
    result = 2
  } else if (
    (angle >= 135 && angle <= 180) ||
    (angle >= -180 && angle < -135)
  ) {
    if (Math.abs(dx) > 50) {
      result = 3
    }
  }
  return result
}

function GetSlideAngle (dx, dy) {
  return (Math.atan2(dy, dx) * 180) / Math.PI
}
